/*******************************************************************************
 * Copyright (c) 2011 Irineu Martins de Lima Moura (imlm2).
 * This file is part of JBeat.
 * 
 *     JBeat is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Lesser General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     JBeat is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Lesser General Public License for more details.
 * 
 *     You should have received a copy of the GNU Lesser General Public License
 *     along with JBeat.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Contributors:
 *     Irineu Martins de Lima Moura (imlm2) - initial API and implementation
 ******************************************************************************/
package br.ufpe.cin.imlm2.jbeat.soot.traps;

import java.util.Collections;
import java.util.Iterator;
import java.util.Set;

import soot.Body;
import soot.FastHierarchy;
import soot.Scene;
import soot.SootClass;
import soot.Trap;
import soot.Unit;
import soot.util.Chain;
import br.ufpe.cin.imlm2.jbeat.soot.icpoints.tags.InterconnectingPointsTag;

public class TrapManager extends soot.TrapManager {

	
	public static boolean isExceptionCaughtAt(SootClass e, Unit u, Body b)
	{
		FastHierarchy h = Scene.v().getFastHierarchy();
		Chain<Unit> units = b.getUnits();
		Iterator<Trap> trapsIt = b.getTraps().iterator();
		InterconnectingPointsTag ipt = (InterconnectingPointsTag) b.getTag(InterconnectingPointsTag.TAG_NAME);
		Set<Trap> points;
		if(ipt != null) points = ipt.getInterconnectingPoints();
		else points = Collections.emptySet();
		
		while (trapsIt.hasNext())
		{
			Trap t = trapsIt.next();

			if(!points.contains(t)) {

				if (h.isSubclass(e, t.getException()))
				{
					Iterator<Unit> it = units.iterator(t.getBeginUnit(),
							units.getPredOf(t.getEndUnit()));
					while (it.hasNext())
						if (u.equals(it.next()))
							return true;
				}
			}
		}
		return false;
	}
}
